<template>
	<view class="rootview">
		<form @submit="modifySave">
			<view class="">
				<text>姓名：</text>
			</view>
			<view>
				<input type="text" name="name" :value="detailData.name" placeholder="请输入姓名" />
			</view>
			<view class="">
				<text>电话：</text>
			</view>
			<view>
				<input type="text" name="tel" :value="detailData.tel" placeholder="请输入电话" />
			</view>
			<button form-type="submit">保存</button>
		</form>
	</view>
</template>

<script>
	import db from '@/js_sdk/uni-clientDB/index.js';
	const dbCmd = db.command;
	let docid;
	export default {
		data() {
			return {
				detailData: [],
			};
		},
		onLoad(event) {
			// console.log("event",event);
			docid = event.id
			//TODO 判断docid是否undefined
			this.getDetail();
		},
		methods: {
			getDetail() {
				var that = this;
				uniCloud.callFunction({
					name: 'uni-clientDB',
					data: {
						command: db
							.collection('phonebook')
							.where({
								_id: docid
							})
							.field({
								extra: false
							})
							.get()
					},
					success(res) {
						console.log(res.result);
						if (res.result.data.length === 0) {
							uni.showModal({
								content: '数据不存在，可能已经被删除',
								showCancel: false,
								success() {
									uni.navigateBack();
								}
							});
						} else {
							that.detailData = res.result.data[0];
							// console.log(that.detailData);
						}
					},
					fail(err) {
						console.error(err);
						uni.showModal({
							content: err.message || '服务器连接失败',
							showCancel: false,
							success() {
								uni.navigateBack();
							}
						});
					}
				});
			},
			modifySave: function(e) {
				console.log('submit数据：', e.detail.value)
				var formdata = e.detail.value
				if (!formdata.name) {
					uni.showModal({
						content: '姓名不能为空',
						showCancel: false
					})
					return
				}
				if (!/^\+?[0-9-]{3,20}$/.test(formdata.tel)) {
					uni.showModal({
						content: '电话号码不合法',
						showCancel: false
					})
					return
				}
				uniCloud.callFunction({
					name: 'uni-clientDB',
					data: {
						command: db.collection('phonebook').doc(docid).update(formdata)
					},
					success(res) {
						// console.log(res);
						//redirect方式跳转到新建好的详情页面
						// uni.redirectTo({url:"../detail/detail?id="+docid})
						uni.navigateBack() // 走返回逻辑
						uni.$emit('reloadList')
					},
					fail(err) {
						console.error(err);
						uni.showModal({
							content: err.message || '服务器连接失败',
							showCancel: false
						});
					}
				});
			}
		}
	};
</script>

<style>
	.rootview {
		padding: 15px;
	}
</style>
